//
//  OAuthViewController.swift
//  sina
//
//  Created by DXapple on 15/11/12.
//  Copyright © 2015年 sqlite. All rights reserved.
//
import SVProgressHUD
import UIKit
import AFNetworking
//App Key：3538791731
//App Secret：fb8349e32acda5ed3fd08365ebeb8994
//http://www.itcast.cn grant_type	true	string	请求的类型，填写authorization_code
class OAuthViewController: UIViewController {
    let client_id = "3538791731"
    let redirect_uri = "http://www.itcast.cn"
    let client_secret = "fb8349e32acda5ed3fd08365ebeb8994"
    let webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
     
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        loadOauthPage()
        

    }
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }

    private func loadOauthPage() {
    
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    
    }
    
    
    func setupUI() {
    self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
        
    }
    @objc private func close() {
    dismissViewControllerAnimated(true, completion: nil)
    
    }
    @objc private func fullAccount() {
        
        let jsString = "document.getElementById('userId').value = '847596119@qq.com' , document.getElementById('passwd').value = 'xiaojie1228';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }

    
}



//专门处理weview 所有协议方法
extension OAuthViewController: UIWebViewDelegate{
    func webViewDidFinishLoad(webView: UIWebView) {
//        print(__FUNCTION__ )
        SVProgressHUD.dismiss()

        }
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //协议方法 如果返回bool 一般表示如果为true 表hi当前对象可以正常工作否则就不能
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
         //request.url所有地址  当前url的绝对路径 打印出来的是string
        guard let urlString = request.URL?.absoluteString else {
        return false
        }
        
        if urlString.hasPrefix("https://api.weibo.com") {
        return true
        }
        if !urlString.hasPrefix(redirect_uri) {

            return false
        }
        
        guard let query = request.URL?.query else {
            
            return false
            
        }
        let codeStr = "code="
        let code = query.substringFromIndex(codeStr.endIndex)
        print(code)
        print(query)
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in

self.dismissViewControllerAnimated(false, completion: { () -> Void in
    
    NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewControler, object: "welcom")
})
            
        }
        return false
        
    }
    

}






